package com.example.tests;

import com.example.pages.LoginPage;
import com.example.pages.MyPageFactory;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.TestRule;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.openqa.selenium.Alert;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import ru.esteru.selenium.factory.WebDriverFactory;

import java.io.File;
import java.io.IOException;

public class BaseTest {

    public WebDriver driver;
    public boolean acceptNextAlert = true;
    public String baseUrl;

    @Before
    public void setUp() throws Exception {
        driver = WebDriverFactory.getDriver(DesiredCapabilities.firefox());
        baseUrl = "http://localhost/";
    }

    public LoginPage goToHomePage() {
        driver.get(baseUrl + "php4dvd");
        return MyPageFactory.getPage(driver, LoginPage.class);
    }

    @Rule
    public TestRule screenshotRule = new TestWatcher() {

        @Override
        protected void failed(Throwable e, Description description) {
            captureScreenshot(description.getMethodName());
        }
    };


    private void captureScreenshot(String name) {
        File screenshot = ((TakesScreenshot) driver)
                .getScreenshotAs(OutputType.FILE);
        String path = "./target/screenshots/" + name +"_"+ screenshot.getName();
        try {
            FileUtils.copyFile(screenshot, new File(path));
        } catch (IOException e) {

        }
    }


}
